import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:hitutor/UI/GroupClass/GroupClass.dart';
import 'package:hitutor/UI/HiNote/HiNote.dart';
import 'package:hitutor/UI/Home/HomeBody.dart';
import 'package:hitutor/UI/Home/MemberBody.dart';
import 'package:hitutor/UI/Home/UploadTM/UploadTMBody.dart';
import 'package:hitutor/UI/Member/MyLesson/ClassList.dart';
import 'package:hitutor/UI/Member/HelpCenter.dart';
import 'package:hitutor/UI/Member/MyOrder/MyOrderList.dart';
import 'package:hitutor/UI/NoticeAndMessage/NewMessageList.dart';
import 'package:hitutor/UI/NoticeAndMessage/NoticeList.dart';
import 'package:hitutor/UI/WebPage.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:share/share.dart';

import 'Calendar.dart';
import 'OrderClass/ClassBody.dart';

class Home extends StatefulWidget {
  int page;
  bool register;
  static GlobalKey<HomeBodyState> homeKey = GlobalKey<HomeBodyState>();
  static GlobalKey<ClassBodyState> classKey = GlobalKey<ClassBodyState>();
  static GlobalKey<CalendarState> calendarKey = GlobalKey<CalendarState>();

  Home({this.page = 0, this.register = false});

  @override
  State<StatefulWidget> createState() {
    return _Home();
  }
}

class _Home extends State<Home> {
  static int HOME = 0;
  static int CLASS = 1;
  static int UPLOAD = 2;
  static int CALENDAR = 3;
  static int MEMBER = 4;
  int pageBody = HOME;
  bool menuOpen = false;

  int unreadNum = 0;
  String chatUrl = "";
  static GlobalKey ChatState = GlobalKey();

  openMenu() {
    SmartDialog.show(
      widget: Menu(context, unreadNum: unreadNum, onSwitchPage: (page) => switchPage(page), onOpenIm: startChat),
      alignmentTemp: Alignment.centerLeft,
    );
  }

  closeMenu() {
    SmartDialog.dismiss();
  }

  switchPage(int page) {
    if (page == HOME) {
      print("HOME:resume");
      Home.homeKey.currentState?.getHomePage(true);
    }
    if (page == CLASS) {
      print("CLASS:resume");
      Home.classKey.currentState?.getData();
    }
    if (page == CALENDAR) {
      print("CALENDAR:resume");
      Home.calendarKey.currentState?.getClassDay();
      Home.calendarKey.currentState?.getDateMonth();
    }
    pageBody = page;
    setState(() {});
  }

  ///合併到getHomepage
  // getShareLink() {
  //   HttpGo(context).get("/Information/GetShareLink?studentId=${Global.studentId}", {}, (data) {
  //     shareLink = data["shareLink"];
  //   }, (code, error) {
  //     showToast(error);
  //   }, showLoading: false);
  // }

  //todo 删除
  connectIM() async {
    // PinChat.connect(userId: Global.userId).then((value) {
    //   print("imkit:success");
    //   updateIMUserInfo(Global.userId);
    // }).catchError((e) {
    //   showToast(e.toString());
    // });
  }

  updateIMUserInfo(String nickname) {
    // PinChat.updateMyProfile(nickname: nickname, avatarUrl: Global.winterImage).then((value) => print("imkit:updateIMUserInfo-success"));
  }

  startChat() {
    // PinChat.goChatRoomList();
    PageUtil().open(context, WebPage("", chatUrl));
  }

  Future _findLocalPath() async {
    MethodChannel _channel = MethodChannel('PathUtil');
    if (Theme.of(context).platform == TargetPlatform.android) {
      // await getExternalStorageDirectory()
      Global.downloadPath = await _channel.invokeMethod("getDownloadPath");
    } else {
      // final directory = await getApplicationSupportDirectory();
      final directory = await getApplicationDocumentsDirectory();
      Global.downloadPath = directory.path;
    }
    print("getDownloadPath:${Global.downloadPath}");
  }

  @override
  initState() {
    super.initState();
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) async {
      Permission.storage.request();
      var status = await Permission.storage.status;
      if (status.isDenied) {
        //沒有儲存權限
      }
      if (widget.register) {
        showBtn1Dialog(context, "", Global.regTip, btnText: "我知道了");
      }
      _findLocalPath();
      // connectIM();
      switchPage(widget.page);
    });
  }

  @override
  Widget build(BuildContext context) {
    print("----------Home build------------");
    return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: MyColor.White,
        appBar: AppBar(toolbarHeight: 0, backgroundColor: MyColor.Transfer, elevation: 0, systemOverlayStyle: SystemUiOverlayStyle.dark),
        body: Column(children: [
          Container(
              height: 44,
              child: AppBar(
                  backgroundColor: MyColor.Transfer,
                  toolbarHeight: 44,
                  title: LocalImage("hi_logo.png", height: 32),
                  centerTitle: true,
                  elevation: 0,
                  leading: Builder(builder: (BuildContext context) {
                    return LocalImage("menu-alt.png", padding: EdgeInsets.all(10), onTap: openMenu);
                  }),
                  actions: [
                    LocalImage("share-alt2.png", padding: EdgeInsets.all(10), onTap: () {
                      if (Global.shareLink.isNotEmpty) Share.share("${Global.shareLink}");
                    }),
                    Stack(alignment: Alignment.center, key: ChatState, children: [
                      LocalImage("chat-alt3.png", padding: EdgeInsets.all(10), onTap: startChat),
                      Positioned(child: unreadDot(unreadNum), right: 0, top: 8)
                    ]),
                    Container(width: 8)
                  ])),
          Expanded(
              child: Stack(children: [
            Column(children: [
              Expanded(
                  child: Stack(
                children: [
                  Visibility(
                      child: HomeBody(
                          key: Home.homeKey,
                          onToCalendar: () {
                            switchPage(CALENDAR);
                          },
                          onGetHomePage: (data) {
                            chatUrl = data["passport"]; //聊天链接
                            unreadNum = data["unreadMessageCount"]; //未读消息
                            setState(() {});
                          }),
                      visible: pageBody == HOME,
                      maintainState: true),
                  Visibility(
                      visible: pageBody == CLASS,
                      maintainState: true,
                      child: ClassBody(
                          key: Home.classKey,
                          onToCalendar: () {
                            switchPage(CALENDAR);
                          })),
                  Visibility(child: UploadTMBody(), visible: pageBody == UPLOAD, maintainState: true),
                  Visibility(
                      visible: pageBody == CALENDAR,
                      maintainState: true,
                      child: Calendar(
                          key: Home.calendarKey,
                          onAddClass: () {
                            switchPage(CLASS);
                          })),
                  Visibility(child: MemberBody(), visible: pageBody == MEMBER, maintainState: true),
                ],
              )),
              Container(height: 1, color: MyColor.EE),
              Container(
                  color: MyColor.White,
                  child: Row(children: [
                    bottomBtn("首頁", icon: "home-alt3.png", selectedIcon: "home-alt3-active.png", selected: pageBody == HOME, onTap: () {
                      switchPage(HOME);
                    }),
                    bottomBtn("訂課", icon: "bookmark-alt.png", selectedIcon: "bookmark-alt-active.png", selected: pageBody == CLASS,
                        onTap: () {
                      switchPage(CLASS);
                    }),
                    bottomBtn("上傳教材", icon: "upload-alt2.png", selectedIcon: "upload-alt2-active.png", selected: pageBody == UPLOAD,
                        onTap: () {
                      switchPage(UPLOAD);
                    }),
                    bottomBtn("行事曆", icon: "clock-alt2.png", selectedIcon: "clock-alt2-active.png", selected: pageBody == CALENDAR,
                        onTap: () {
                      switchPage(CALENDAR);
                    }),
                    bottomBtn("會員", icon: "face-i-d.png", selectedIcon: "face-i-d-active.png", selected: pageBody == MEMBER, onTap: () {
                      switchPage(MEMBER);
                    }),
                  ]))
            ])
          ]))
        ]));
  }
}

class Menu extends StatelessWidget {
  static int HOME = 0;
  static int CLASS = 1;
  static int UPLOAD = 2;
  static int CALENDAR = 3;
  static int MEMBER = 4;

  Function(int page) onSwitchPage;
  Function() onOpenIm;
  BuildContext _context;
  int unreadNum;

  Menu(this._context, {required this.onSwitchPage, required this.onOpenIm, this.unreadNum = 0});

  closeMenu() {
    SmartDialog.dismiss();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        color: MyColor.F3,
        width: 250,
        alignment: Alignment.centerLeft,
        child: Column(mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [
          AppBar(toolbarHeight: 0, systemOverlayStyle: SystemUiOverlayStyle.light, backgroundColor: MyColor.Transfer, elevation: 0),
          Container(
              width: 44,
              margin: EdgeInsets.only(left: 12),
              child: LocalImage("cross_gray.png", padding: EdgeInsets.all(10), onTap: closeMenu)),
          MenuBtn("首頁", onTap: () {
            closeMenu();
            onSwitchPage(HOME);
          }),
          MenuBtn("公告", onTap: () {
            closeMenu();
            PageUtil().open(_context, NoticeList());
          }),
          MenuBtn("最新消息", onTap: () {
            closeMenu();
            PageUtil().open(_context, NewMessageList());
          }),
          MenuBtn("訂課", onTap: () {
            closeMenu();
            onSwitchPage(CLASS);
          }),
          MenuBtn("上傳教材", onTap: () {
            closeMenu();
            onSwitchPage(UPLOAD);
          }),
          MenuBtn("行事曆", onTap: () {
            closeMenu();
            onSwitchPage(CALENDAR);
          }),
          MenuBtn("我的課程", onTap: () {
            closeMenu();
            PageUtil().open(_context, ClassList());
          }),
          MenuBtn("我的訂單", onTap: () {
            closeMenu();
            PageUtil().open(_context, MyOrderList(key: Global.myOrderKey));
          }),
          Row(children: [
            Expanded(
                child: MenuBtn("訊息平台", onTap: () {
              closeMenu();
              onOpenIm();
            })),
            Container(margin: EdgeInsets.only(right: 16), child: unreadDot(unreadNum))
          ]),
          MenuBtn("HiNote", onTap: () {
            closeMenu();
            PageUtil().open(_context, HiNote());
          }),
          MenuBtn("團班課程", onTap: () {
            closeMenu();
            PageUtil().open(_context, GroupClass());
          }),
          MenuBtn("會員", onTap: () {
            closeMenu();
            onSwitchPage(MEMBER);
          }),
          MenuBtn("幫助中心", onTap: () {
            closeMenu();
            PageUtil().open(_context, HelpCenter());
          }),
        ]));
  }
}

class MenuBtn extends StatelessWidget {
  String text;
  Function()? onTap;

  MenuBtn(this.text, {this.onTap});

  @override
  Widget build(BuildContext context) {
    return TextBtn(text,
        onTap: onTap,
        margin: EdgeInsets.fromLTRB(28, 10, 0, 10),
        alignment: Alignment.centerLeft,
        style: TextStyle(fontSize: 14, color: Color(0xff364e8b), fontWeight: FontWeight.bold));
  }
}

class bottomBtn extends StatelessWidget {
  String icon;
  String selectedIcon;
  String text;
  bool selected;
  Function()? onTap;

  bottomBtn(this.text, {required this.icon, required this.selectedIcon, required this.selected, this.onTap});

  @override
  Widget build(BuildContext context) {
    return Expanded(
        child: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: onTap,
            child: Column(children: [
              LocalImage(selected ? selectedIcon : icon, width: 24, padding: EdgeInsets.all(4)),
              Text(text, style: TextStyle(fontSize: 12, color: selected ? MyColor.BlueHome : MyColor.C7D)),
              Container(height: 8),
            ])));
  }
}

class unreadDot extends StatelessWidget {
  int unreadNum;

  unreadDot(this.unreadNum);

  @override
  Widget build(BuildContext context) {
    return unreadNum > 0
        ? Container(
            height: 18,
            padding: EdgeInsets.symmetric(horizontal: 4),
            constraints: BoxConstraints(minWidth: 18),
            alignment: Alignment.center,
            decoration: BoxDecoration(color: MyColor.Red, borderRadius: BorderRadius.circular(9)),
            child: Text(unreadNum > 99 ? "99+" : unreadNum.toString(), style: TextStyle(fontSize: 10, color: MyColor.White)))
        : Container();
  }
}
